import { defineStore } from 'pinia'
import axios from 'axios'

export const useCityStore = defineStore('city', {
  state: () => ({
    startCity: '', // 起点城市
    endCity: '', // 终点城市
    placeData: [], // 存储接口返回的数据
    selectedPlaceName: '', // 选中的位置名称
    currentAddress: '' // 新增状态，保存当前地址
  }),
  actions: {
    setCity(cityName) {
      this.city = cityName
    },
    setStartCity(cityName) {
      this.startCity = cityName
    },
    setEndCity(cityName) {
      this.endCity = cityName
    },
    async updateStartCityAndRequest(newCity) {
      this.setStartCity(newCity)
      await this.fetchPlaces()
    },
    async fetchPlaces() {
      const params = {
        region: this.startCity,
        keywords: this.startCity, // 默认使用城市名作为关键词
        key: '5313c642a37b975fe995e5941dcb11e4'
      }

      try {
        const response = await axios.get(`https://restapi.amap.com/v3/place/text`, { params })

        if (response.status === 200 && response.data.status === '1') {
          this.placeData = response.data.pois // 更新placeData状态
        } else {
          const message = response.data.info || '请求异常'
          console.error(message)
        }
      } catch (err) {
        console.error(err)
      }
    },
    async fetchPlacesByKeyword(searchKeyWord) {
      const params = {
        region: this.startCity,
        keywords: searchKeyWord || this.startCity, // 如果searchKeyWord为空，则使用startCity作为关键词
        key: '7277263e574b19aa3f7b9399843c0fd0'
      }

      try {
        const response = await axios.get(`https://restapi.amap.com/v3/place/text`, { params })

        if (response.status === 200 && response.data.status === '1') {
          this.placeData = response.data.pois // 更新placeData状态
        } else {
          const message = response.data.info || '请求异常'
          console.error(message)
        }
      } catch (err) {
        console.error(err)
      }
    },
    setSelectedPlaceName(name) {
      this.selectedPlaceName = name
    },
    async updateCurrentAddress(address) {
      this.currentAddress = address
      console.log(address)
    }
  }
})
